/**
 * 
 */
package com.yzt.insys.control;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.yzt.insys.common.PageNavation;
import com.yzt.insys.dto.UserDto;
import com.yzt.insys.service.DeptService;
import com.yzt.insys.service.PowerService;
import com.yzt.insys.service.RoleService;
import com.yzt.insys.service.UserService;
import com.yzt.insys.util.MD5Util;
import com.yzt.insys.util.UserUtil;

/**
 * @作者 zsf
 * @时间 2013-6-20
 */
@Scope("prototype")
@Controller
@RequestMapping("/user")
public class UserControl extends BaseControl {

	@SuppressWarnings("unused")
	private Logger log=Logger.getLogger(getClass());
	
	@Resource
	@Qualifier("userService")
	private UserService uService;
	@Resource
	@Qualifier("deptService")
	private DeptService dService;
	@Resource
	@Qualifier("roleService")
	private RoleService rService;
	@Resource
	private PowerService pwService;
	
	/**
	 * 获取用户集合
	 */
	@ResponseBody
	@RequestMapping(value="/getData",method={RequestMethod.POST,RequestMethod.GET})
	public String getData(PageNavation page){
		paramMap=getParamMap();
		page.setParamMap(paramMap);
		page.setCurrentPage(Integer.parseInt(paramMap.get("page").toString()));//获取当前页码
		page.setPageSize(Integer.parseInt(paramMap.get("rows").toString()));//获取每页显示数量
		page.setStartIndex((page.getCurrentPage()-1)*page.getPageSize());//设置查询开始位置
		int totalCount=uService.queryUserCount();//获取总记录数
		List<UserDto> userList=uService.queryModelList(page);//获取集合对象
		StringBuilder sb=new StringBuilder();
		sb.append("{\"total\":"+totalCount+",");
		sb.append("\"rows\":"+JSON.toJSONString(userList)+"}");
		return sb.toString();
	}
	/**
	 * 跳转添加用户页面
	 */
	@RequestMapping("/toAdd")
	public String toAdd(){
		reqAddAttr("deptList",dService.queryModelList(getPage()));	
		reqAddAttr("roleList",rService.queryModelList(getPage()));
		return forward_toAdd();
	}
	/**
	 * 添加用户
	 */
	@ResponseBody
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Object add(UserDto u,Long[] roleId,Long[] styleIds){
		u.setCreatedBy(getUserFromSession().getId());
		u.setUserPwd(MD5Util.encode(u.getUserPwd()));
		boolean flg=uService.insert(u);
		if(roleId!=null&&roleId.length>0){
			paramList.clear();
			for(Long id:roleId){
				paramList.add(id);
			}
			paramMap.clear();
			paramMap.put("userId",u.getId());
			paramMap.put("roleIds",paramList);
			uService.insertRole(paramMap);
		}
		return flg;
	}
	/**
	 * 跳转修改用户页面
	 * @param id
	 * @param title
	 * @return
	 */
	@RequestMapping("/toUpd/{id}")
	public String toUpd(@PathVariable("id") Long id){
		reqAddAttr("roleList",rService.queryModelList(getPage()));
		reqAddAttr("deptList",dService.queryModelList(getPage()));
		reqAddAttr("user",uService.queryByPK(id));
		return forward_toUpd();
	}
	/**
	 * 修改用户
	 */
	@ResponseBody
	@RequestMapping(value="/upd",method=RequestMethod.POST)
	public Object updUser(UserDto user,Long[] roleId){
		if(user.getUserPwd()!=null&&user.getUserPwd()!=""){
			user.setUserPwd(MD5Util.getEncode("MD5", user.getUserPwd()));
		}else{
			user.setUserPwd(null);
		}
		boolean flg=uService.updateByPK(user);
		//删除该用户之前的权限
		uService.delRoleByPKUser(user.getId());
		if(roleId!=null&&roleId.length>0){
			paramList.clear();
			for(Long id:roleId){
				paramList.add(id);
			}
			paramMap.clear();
			paramMap.put("userId",user.getId());
			paramMap.put("roleIds",paramList);
			uService.insertRole(paramMap);
		}
		return flg;
	}
	/**
	 * 删除用户
	 */
	@ResponseBody
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Object delUser(@RequestParam("ids")List<Long> ids){
		//先删除用户角色表信息
		rService.deleteUrByPKUsers(ids);
		return uService.deleteByPKs(ids);
	}
	
	/**
	 * 根据部门id查询用户集合
	 * @param deptId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getUserByDept",method=RequestMethod.POST)
	public Object getUserByDept(@RequestParam("deptId") Long deptId){
		return uService.queryUserByDept(deptId);
	}
	/**
	 * 检验用户名是否存在
	 */
	@ResponseBody
	@RequestMapping(value="/checkUserName",method=RequestMethod.POST)
	public Object checkUserName(){
		return uService.isUserNameExist(getParamMap());
	}
	
	@ResponseBody
	@RequestMapping(value="/checkUserNumber")
	public Object checkUserNumber(){
		return uService.isUserNumberExist(getParamMap());
	}
	/**
	 * 跳转到查看用户对象页面
	 */
	@RequestMapping(value="/view/{id}")
	public Object view(@PathVariable("id") Long id){
		reqAddAttr("user",uService.queryByPK(id));
		return forward_toView();
	}
	/**
	 * 修改密码
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updPwd",method={RequestMethod.POST})
	public Object updPwd(@RequestParam("oldPwd")String oldPwd,@RequestParam("newPwd")String newPwd){
		UserDto user=UserUtil.getUserFromSession(session);
		if(oldPwd==null||oldPwd.trim().equals("")){
			return "原始密码不能为空！";
		}
		if(newPwd==null||newPwd.trim().equals("")){
			return "新密码不能为空！";
		}
		if(user.getUserPwd().equals(oldPwd)){
			user.setUserPwd(newPwd);
			return ""+uService.updateByPK(user);
		}else{
			return "原始密码错误！";
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public String upload(MultipartHttpServletRequest request,String editor) {
		List<MultipartFile> files = request.getFiles("file");
		String rooePath="/resources";
		String basePath=session.getServletContext().getRealPath(rooePath);
		String flg="false";
		try {
			for (MultipartFile file : files) {
				if (file.isEmpty()) {
					continue;
				}
				String suffix = file.getOriginalFilename();
				suffix = suffix.substring(suffix.lastIndexOf("."));
				String relativePath="/uploadFiles/images/";
				String fileName=UUID.randomUUID().toString()+suffix;
				FileUtils.copyInputStreamToFile(file.getInputStream(),new File(basePath+relativePath+fileName));
				flg=rooePath+relativePath+fileName;
				if(editor!=null&&editor.equals("editor")){
					flg="{\"error\":0,\"url\":\"/ah"+flg+"\"}";
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flg;
	}
}
